import axios from "axios"
import { ShowErrorMsg } from "../utils/message"
// export const baseURL = "http://192.168.58.66:3000/" // 本地接口
// export const baseURL = 'http://192.168.58.232:3000/'   // 本地接口
export const baseURL = 'http://81.69.235.62:3000/'   // 线上接口

const request = axios.create({
	baseURL: baseURL,
	timeout: 10000,
	headers: {},
})

// 拦截器   Interceptors
// Add a request interceptor  请求拦截器
request.interceptors.request.use(
	function (config) {
		// 发送到后端
		const token = localStorage.getItem("AppToken")
		// config.headers.token = token?.replace(/"/g, "")
		if (
			config.url != "https://m.maizuo.com/gateway" &&
			config.url != "http://120.26.90.83:3000/captcha/sent" &&
			config.url != "http://120.26.90.83:3000/captcha/verify"
		) {
			config.headers.token = token?.replace(/"/g, "")
		}

		return config
	},
	function (error) {
		ShowErrorMsg("请求失败")
		// 请求失败
		return Promise.reject(error)
	}
)

// Add a response interceptor  响应拦截器
request.interceptors.response.use(
	function (response) {
		// 响应成功
		// 手机端 没有任何的成功提示

		return response
	},
	function (error) {
		ShowErrorMsg("响应失败")
		// 响应失败  503
		return Promise.reject(error)
	}
)

// GET 请求
export const GET = (url: string, params?: object, headers?: object) => {
	return new Promise((resolve, reject) => {
		request({
			url,
			method: "GET",
			params: params,
			headers,
		})
			.then((result) => {
				resolve(result.data)
			})
			.catch((err) => {
				reject(err)
			})
	})
}

// POST 请求
export const POST = (
	url: string,
	data?: object,
	params?: object,
	headers?: object
) => {
	return new Promise((resolve, reject) => {
		request({
			url,
			method: "POST",
			data: data,
			params: params,
			headers,
		})
			.then((result) => {
				resolve(result.data)
			})
			.catch((err) => {
				reject(err)
			})
	})
}

export { request }
